import {
  ParamsType,
  getCommentsByIdAPI,
  submitCommentAPI,
  commentLikeAPI,
  commentDislikeAPI,
} from '@/api/comment';
import { AppDispatch } from '..';
import { CommentType } from '../redurce/comment';

export const getArticleComByIdAction = (params: ParamsType) => {
  return async (dispatch: AppDispatch) => {
    const res = await getCommentsByIdAPI(params);
    dispatch({ type: 'comment/saveLoading', payload: true });
    dispatch({ type: 'comment/saveList', payload: res.data.results });
    dispatch({ type: 'comment/saveLoading', payload: false });
  };
};

//清除的action
export const clearCommentsAction = () => {
  return {
    type: 'comment/saveList',
    payload: [],
  };
};

// 4. 定义action函数
export const saveOriginCommentAction = (commentData: CommentType) => {
  return {
    type: 'comment/saveOrigiComment',
    payload: commentData,
  };
};

// 清除
export const clearOriginCommentAction = () => {
  return {
    type: 'comment/clearOrigiComment',
  };
};

// 发表评论

export const submitCommentAction = (
  target: string,
  content: string,
  art_id?: string
) => {
  return async () => {
    const res = await submitCommentAPI({ target, content });
    console.log('res  ----->  ', res);
  };
};

export const getCommentByIdAction = (com_id: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getCommentsByIdAPI({ type: 'c', source: com_id });
    console.log('res11  ----->  ', res);
    dispatch({ type: 'comment/saveReplyComment', payload: res.data });
  };
};

export const clearReplyAction = () => {
  return {
    type: 'comment/saveReplyComment',
    payload: {
      end_id: '',
      last_id: '',
      results: [],
      total_count: 0,
    },
  };
};

// 点赞或者取消点赞
export const likeCommentAction = (id: string, is_liking: boolean) => {
  return async (dispatch: AppDispatch) => {
    if (!is_liking) {
      await commentLikeAPI(id);
      dispatch({ type: 'comment/updateCommentById', payload: id });
      return;
    }
    await commentDislikeAPI(id);
    dispatch({ type: 'comment/updateCommentById', payload: id });
  };
};

export const likeReplyCommentsAction = (id: string, isLiking: boolean) => {
  return async (dispach: AppDispatch) => {
    if (!isLiking) {
      await commentLikeAPI(id);
      dispach({ type: 'comment/updateReplyCommentById', payload: id });
      return;
    }
    await commentDislikeAPI(id);
    dispach({ type: 'comment/updateReplyCommentById', payload: id });
  };
};

// 3.  定义一个更新原始数据的acton
export const likeOriginCommentsAction = (id: string, isLiking: boolean) => {
  return async (dispatch: AppDispatch) => {
    if (!isLiking) {
      await commentLikeAPI(id);
      dispatch({ type: 'comment/updateOriginComment' });
      return;
    }
    await commentDislikeAPI(id);
    dispatch({ type: 'comment/updateOriginComment' });
  };
};
